var app = getApp();
Page({
  data: {
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    circular: true,
    productData: [],
    proCat:[],
    page: 2,
    index: 2,
    brand:[],
    // 滑动
    imgUrl: [],
    kbs:[],
    lastcat:[],
    goodsurl: app.d.hostUrl + app.d.goodsurl,
    ablumurl: app.d.hostUrl + app.d.ablumurl,
    store: app.d.store,
    center_latitude:'',
    center_longitude:'',
    miaoshu:'',
    canorder:0,
    showShouquan: true,
    markers: [],
    covers: [],
    circles: [],
    king:[],
    zun:[],
    userInfo:[],
    marqueePace: 1,//滚动速度
    marqueeDistance: 0,//初始滚动距离
    marquee_margin: 30,
    size: 14,
    text_interval: 20, // 时间间隔
    text:'',
    tlen:0,
    invite:0,
  },
  go_product_list:function(){
    wx.navigateTo({
      url: '/pages/product/naodong?id=18'
    })
  },
  chooseLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        //console.log(res)
        that.setData({
          covers: [{
            iconPath: "/images/location.png",
            latitude: res.latitude,
            longitude: res.longitude,
          }],
          locationAddress: res.address
        })

        var distance = that.getDistance(that.data.center_latitude, that.data.center_longitude, res.latitude, res.longitude);
        //console.log(distance);

      }
    })
  },
  getDistance: function (lat1, lng1, lat2, lng2) {
    lat1 = lat1 || 0;
    lng1 = lng1 || 0;
    lat2 = lat2 || 0;
    lng2 = lng2 || 0;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0);//单位：米

  },
//跳转商品列表页   
listdetail:function(e){
    wx.navigateTo({
      url: '../listdetail/listdetail?title='+e.currentTarget.dataset.title,
      success: function(res){
        // success
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  buy_vip1: function (e) {
    console.log(app.globalData.phone);
    if (app.globalData.phone == undefined) {
      wx.navigateTo({
        url: '../user/company?cartId=vip1'
      });
      return;
    }  
    if(app.globalData.phone == ''){
      wx.navigateTo({
        url: '../user/company?cartId=vip1'
      });
      return;
    }
    wx.navigateTo({
      url: '../product/vip1'
    });
  },
  buy_vip2: function (e) {
    console.log(app.globalData.phone);
    if (app.globalData.phone == '') {
      wx.navigateTo({
        url: '../user/company?cartId=vip2'
      });
      return;
    }
    wx.navigateTo({
      url: '../product/vip2'
    });
  },
  scan() {
    wx.scanCode({
      success: (res) => {
        console.log("扫码结果");
        console.log(res);
        console.log(res.path);
        wx.navigateTo({
          url: '/' + res.path
        });
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
addShopCart: function (e) { //添加到购物车
  var that = this;
  console.log(app.globalData.userInfo);
  wx.request({
    url: app.d.hostUrl + 'wapi/cart_add.html',
    method: 'post',
    data: {
      uid: app.d.userId,
      pid: e.currentTarget.dataset.productid,
      num: 1,
      seesionid: app.globalData.userInfo.sessionId,
      openid: app.globalData.userInfo.openid,
    },
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    success: function (res) {
      // //--init data
      var data = res.data;
      if (data.status == 0) {
        var ptype = e.currentTarget.dataset.type;
        if (ptype == 'buynow') {
          wx.redirectTo({
            url: '../order/pay?cartId=' + data.cart_id
          });
          return;
        } else {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          });
        }
      } else {
        wx.showToast({
          title: data.err,
          duration: 2000
        });
      }
    },
    fail: function () {
      // fail
      wx.showToast({
        title: '网络异常！',
        duration: 2000
      });
    }
  });
},

  changeIndicatorDots: function (e) {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },
  changeAutoplay: function (e) {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },
  intervalChange: function (e) {
    this.setData({
      interval: e.detail.value
    })
  },
  durationChange: function (e) {
    this.setData({
      duration: e.detail.value
    })
  },
  getLocation: function () {
    var that = this;
    wx.getLocation({
        success: function (res) {
          //console.log(res);
          that.setData({
            hasLocation: true,
            location: res.latitude + ',' + res.longitude
          });
        }
      })
  },
   bindGetUserInfo: function (e) {
     var that = this;
     app.getUserInfo(function (userInfo) {
       //更新数据
       that.setData({
         userInfo: userInfo,
         loadingHidden: true
       });
       that.setData({
         showShouquan: false,
       });
        return false;
     });
    　　//getApp().globalData.userInfo = e.detail.userInfo     //将授权信息传递给全局变量
        that.setData({
          showShouquan: false,
        })
  },
  onLoad: function (options) {
    var that = this;
    //options.scene = 'invite%3D34';
    if (options.scene != undefined) {
      const scene = decodeURIComponent(options.scene);
      var args = scene.split('&');
      var invite_data = args[0].split('=');
      that.setData({
        invite: invite_data[1],
      });
    }
    //this.getLocation();
    // app.globalData.userInfo

  
    // 查看是否授权
    　　wx.getSetting({
      　　　　success: function (res) {
        　　　if (res.authSetting['scope.userInfo']) {
             app.getUserInfo(function (userInfo) {
                  //更新数据
                  that.setData({
                    userInfo: userInfo,
                    loadingHidden: true
               })
                });
                that.setData({
                  showShouquan: true,
                })
        　　　　}else{
                
                wx.navigateTo({
                  url: '../user/shouquan?invite=' + that.data.invite,
                })
              }
      　　}
    })

    
    wx.request({
      url: app.d.hostUrl + 'wapi/index.html',
      method:'post',
      data: { 
        //seesionid: app.globalData.userInfo.sessionId,
        //openid: app.globalData.userInfo.openid,
        //invite: that.data.invite,
      },
      header: {
        'Content-Type':  'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var ggtop = res.data.ad;
        var pclass = res.data.class;
        var recommend = res.data.recommend;
        var gonggao = res.data.gonggao;
        var text = gonggao.title;
        var tlen = text.length;

        var length = tlen * that.data.size;//文字长度
        var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
        that.setData({
          length: length,
          windowWidth: windowWidth
        });
        that.scrolltxt();



        var king = [];
        if (res.data.king != null) {
          king = res.data.king;
        }
        /**var zun = [];
        if (res.data.zun != null) {
          zun = res.data.zun;
        }**/
        
        //var course = res.data.course; 
        //that.initProductData(data);

        wx.setNavigationBarTitle({
          title: res.data.lat.site_name
        });
        wx.setStorage({
          key: "king",
          data: king,
        });
        /**wx.setStorage({
          key: "zun",
          data: zun
        });**/
        that.setData({
          king_price: res.data.lat.king_price,
          imgUrls:ggtop,
          pclass: pclass,
          productData: recommend,
          text: text,
          tlen: tlen,
          king:king,
          //zun:zun,
          
        });
        if (app.globalData.phone && app.globalData.phone != '') {
          that.setData({
            phone: app.globalData.phone,
            //vip: vip,
          });
        } else {
          // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          // 所以此处加入 callback 以防止这种情况
          app.phoneCallback = phone => {
            if (phone != undefined) {
              that.setData({
                phone: phone,
              });
            }
          }
          app.vipCallback = vip => {
            that.setData({
              vip: vip,
            });
          }
          app.bankCallback = bank => {
            that.setData({
              bank: bank,
            });
          }
          app.user_idCallback = user_id => {
            that.setData({
              user_id: user_id,
            });
          }
        }
        app.openidCallback = openid => {

          if (that.data.invite > 0){
            wx.request({
              url: app.d.hostUrl + 'wapi/update_invite.html',
              method: 'post',
              data: {
                openid: openid,
                invite: that.data.invite,
              },
              header: {
                'Content-Type': 'application/x-www-form-urlencoded'
              },
              success: function (ret) {
                console.log(ret)
              }
            })
          }
          

          that.setData({
            openid: openid,
          });
        }
        app.sessionidCallback = sessionid => {
          that.setData({
            sessionid: sessionid,
          });
        }

        wx.showLoading({
          title: '加载中',
          duration: 2000
        });
      },
      fail:function(e){
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      },
    })
  },
  onReachBottom: function () {
    var that = this;
    var page = that.data.page;
    wx.request({
      url: app.d.hostUrl + 'wapi/goods_list.html',
      method: 'post',
      data: { page: page },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        var goods_list = res.data.goods_list;
        if (goods_list == '') {
          wx.showToast({
            title: '没有了',
            duration: 2000
          });
          return false;
        }
        //that.initProductData(data);
        that.setData({
          page: page + 1,
          productData: that.data.productData.concat(goods_list)
        });
        //endInitData
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    })
  }, 
  onReady: function () {
    setTimeout(function () {
      wx.hideLoading()
    }, 2000);
  },
  onShow: function () {
    var that = this; 
    /**var length = that.data.tlen * that.data.size;//文字长度
    var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
    console.log(length,windowWidth);
    that.setData({
      length: length,
      windowWidth: windowWidth
    });
    that.scrolltxt();**/// 第一个字消失后立即从右边出现

    that.setData({
      vip: app.globalData.vip,
      phone: app.globalData.phone,
      bank: app.globalData.bank,
    });
  },
  onShareAppMessage: function () {
    return {
      title: '赚钱那些事儿',
      path: '/pages/index/index?scene=invite%3D' + app.globalData.user_id,
      success: function(res) {
        wx.showToast({
          title: '分享成功',
          duration: 2000
        });
      },
      fail: function(res) {
        // 分享失败
      }
    }
  },


  scrolltxt: function () {
    var that = this;
    var length = that.data.length;//滚动文字的宽度
    var windowWidth = that.data.windowWidth;//屏幕宽度
    if (length > windowWidth) {
      var interval = setInterval(function () {
        var maxscrollwidth = length + that.data.marquee_margin;//滚动的最大宽度，文字宽度+间距，如果需要一行文字滚完后再显示第二行可以修改marquee_margin值等于windowWidth即可
        var crentleft = that.data.marqueeDistance;
        if (crentleft < maxscrollwidth) {//判断是否滚动到最大宽度
          that.setData({
            marqueeDistance: crentleft + that.data.marqueePace
          })
        }
        else {
          //console.log("替换");
          that.setData({
            marqueeDistance: 0 // 直接重新滚动
          });
          clearInterval(interval);
          that.scrolltxt();
        }
      }, that.data.text_interval);
    }
    else {
      that.setData({ marquee_margin: "1000" });//只显示一条不滚动右边间距加大，防止重复显示
    }
  },



  //先制作一个canvas标签，再保存成图片
  onSaveImg: function () {
    var that = this;

    wx.request({
      url: app.d.hostUrl + 'wapi/get_qrcode.html',
      method: 'post',
      data: {  },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        //endInitData
      },
      fail: function (e) {
        wx.showToast({
          title: '网络异常！',
          duration: 2000
        });
      }
    })



    const ctx = wx.createCanvasContext('myCanvas');//看回wxml里的canvas标签，这个的myCanvas要和标签里的canvas-id一致

    ctx.clearRect(0, 0, 644, 966);
    ctx.drawImage(that.data.goodsurl + that.data.king.goods_image, 100, 100, 400, 400, 100, 100);
    ctx.setFontSize(26);
    ctx.fillText(that.data.king.goods_name, 100, 540);
    ctx.setTextAlign("center");
    ctx.setFillStyle("#f00");
    ctx.fillText('￥' + that.data.king.now_price, 150, 590);


    ctx.moveTo(100, 610)
    ctx.lineTo(500, 610)
    ctx.setStrokeStyle('#A2A2A2')
    ctx.stroke()
    ctx.draw()

    ctx.setTextAlign("left");
    ctx.setFillStyle("black");
    ctx.setFontSize(18);
    ctx.fillText("长按识别小程序码访问", 100, 650);
    ctx.setFontSize(16);
    ctx.setFillStyle("#A1A1A1");
    ctx.fillText("随意礼品商城", 100, 685);

    ctx.drawImage(that.data.goodsurl + that.data.king.goods_image, 330, 620, 150, 150, 100, 100);

    var self = this;

    ctx.draw(true, setTimeout(function () {     //为什么要延迟100毫秒？大家测试一下
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 646,
        height: 966,
        destWidth: 646,
        destHeight: 966,
        canvasId: 'myCanvas',
        success: function (res) {
          self.data.savedImgUrl = res.tempFilePath;
          self.saveImageToPhoto();
        }
      })
    }, 100))
  },
  //保存图片到相册
  saveImageToPhoto: function () {
    if (this.data.savedImgUrl != "") {
      wx.saveImageToPhotosAlbum({
        filePath: this.data.savedImgUrl,
        success: function () {
          wx.showModal({
            title: '保存图片成功',
            content: '寻人启事已经保存到相册，您可以手动分享到朋友圈！',
            showCancel: false
          });
        },
        fail: function (res) {
          console.log(res);
          if (res.errMsg == "saveImageToPhotosAlbum:fail cancel") {
            wx.showModal({
              title: '保存图片失败',
              content: '您已取消保存图片到相册！',
              showCancel: false
            });
          } else {
            wx.showModal({
              title: '提示',
              content: '保存图片失败，您可以点击确定设置获取相册权限后再尝试保存！',
              complete: function (res) {
                console.log(res);
                if (res.confirm) {
                  wx.openSetting({})      //打开小程序设置页面，可以设置权限
                } else {
                  wx.showModal({
                    title: '保存图片失败',
                    content: '您已取消保存图片到相册！',
                    showCancel: false
                  });
                }
              }
            });
          }
        }
      })
    }
  },


















});